from django.shortcuts import render, redirect, HttpResponse
from medical import models
from medical.utils.pagination import Pagination

from medical.utils.bootstrap import BootStrapModelForm
from medical.utils.form import HospitalModelForm
from django.core.exceptions import ValidationError


# 医院表
def hos_list(request):
    """医院表"""
    queryset = models.hospital.objects.all()

    page_object = Pagination(request, queryset)
    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 生成页码
    }

    return render(request, 'hos_list.html', context)


def hos_add(request):
    """添加医院"""
    title = "添加医院"
    if request.method == "GET":
        form = HospitalModelForm()
        return render(request, 'template.html', {'form': form, "title": title})

    form = HospitalModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/hos/list/')

    return render(request, 'template.html', {'form': form, 'title': title})


def hos_edit(request, nid):
    """编辑医院"""
    row_object = models.hospital.objects.filter(hos_id=nid).first()

    if request.method == "GET":
        form = HospitalModelForm(instance=row_object)
        return render(request, 'hos_edit.html', {'form': form})

    form = HospitalModelForm(data=request.POST, instance=row_object)
    if form.is_valid():  # 如果校验不合法 则弹出错误提示
        # form.instance.字段名 = 值
        form.save()  # form.save是用来添加数据的 默认保存的是用户输入的所有数据
        return redirect('/hos/list/')

    context = {
        "form": form,
    }
    return render(request, 'hos_edit.html', context)


def hos_delete(request, nid):
    models.hospital.objects.filter(hos_id=nid).delete()
    return redirect('/hos/list/')
